package com.lazycat.backend.service.impl.address;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lazycat.backend.mapper.AddressMapper;
import com.lazycat.backend.mapper.UserAddressMapper;
import com.lazycat.backend.pojo.Address;
import com.lazycat.backend.pojo.UserAddress;
import com.lazycat.backend.service.address.FetchAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FetchAddressServiceImpl implements FetchAddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Override
    public JSONObject fetch(Integer userId) {
        QueryWrapper<UserAddress> userAddressQueryWrapper = new QueryWrapper<>();
        userAddressQueryWrapper.eq("user_id", userId);
        List<UserAddress> userAddresses = userAddressMapper.selectList(userAddressQueryWrapper);
        ArrayList<JSONObject> items = new ArrayList<>();
        for (UserAddress userAddress : userAddresses) {
            JSONObject item = new JSONObject();
            Integer addressId = userAddress.getAddressId();
            QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
            addressQueryWrapper.eq("address_id", addressId);
            Address address = addressMapper.selectOne(addressQueryWrapper);
            item.put("address_id", address.getAddressId());
            item.put("tag", address.getTag());
            item.put("address", address.getAddress());
            item.put("contact", address.getContact());
            item.put("phone_number", address.getPhoneNumber());
            items.add(item);
        }
        JSONObject resp = new JSONObject();
        resp.put("addresses", items);
        resp.put("error_message", "success");
        return resp;
    }
}
